package network_programming.np1_socket_and_serversocket;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.*;

/**
 * 判断特定的ip地址是否为垃圾邮件发送者的ip地址（采用线程池）
 * */
public class SpamCheckTreadPool {
    private static final int POOL_SIZE = 4;

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(
                Runtime.getRuntime().availableProcessors() * POOL_SIZE);
        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(new FileInputStream("files\\address.txt")));
        String address = null;
        Set<Future<String>> futureResults = new HashSet<>();    // 存放所有任务执行结果的集合
        while ((address = fileReader.readLine()) != null) {
            LookupTask task = new LookupTask(address);
            Future<String> future = executorService.submit(task);
            futureResults.add(future);  // 存储任务结果
        }
//        for (Future<String> result : futureResults)
//            System.out.println(result.get());   // 如果任务还未完成，get()方法就会阻塞，直到任务完成，返回结果

        while (!futureResults.isEmpty()) {      // 采用轮训方式，不断遍历访问结果集，打印已完成任务的结果
            Iterator<Future<String>> it = futureResults.iterator();
            while (it.hasNext()) {
                Future<String> result = it.next();
                if(result.isDone()) {
                    System.out.println(result.get());
                    it.remove();
                }
            }
        }
        executorService.shutdown();
    }
}

class LookupTask implements Callable<String> {
    public static final String BLACKHOLE = "sbl.spamhaus.org";
    String addr;

    public LookupTask(String addr) {
        this.addr = addr;
    }

    @Override
    public String call(){
        try {
            InetAddress address = InetAddress.getByName(addr);
            byte[] quad = address.getAddress(); // 获取主机ip地址
            StringBuilder query = new StringBuilder(BLACKHOLE);     // 黑洞列表

            // 反转ip地址的字节，并添加黑洞服务的域
            for(byte octet : quad) {
                int unsignedByte = octet < 0 ? octet + 256 : octet;
                query.insert(0, unsignedByte + ".");
            }
            InetAddress.getByName(query.toString());   // 查找该地址
            return addr + " 是已知的垃圾邮件发送者";
        } catch (UnknownHostException e) {
            return addr + " 是合法的邮件发送者";
        }
    }
}
